<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      //数据劫持
      function defineReactive(obj, key, value) {
        //我们需要对value进行深层次的处理
        //调用observe
        observe(value);

        Object.defineProperty(obj, key, {
          //在vm上添加 -data的每一份属性
          get() {
            console.log(value, "读取了");
            return value;
          },
          set(newVal) {
            console.log(newVal, "设置了");
            value = newVal;
          },
        });
      }

      //对数据开始响应式操作
      function observe(obj) {
        //console.log(obj);
        //判断  因为是递归调用 如果obj不是对象或等于null 则直接return 不需要深层次的响应式处理
        if (typeof obj !== "object" || obj === null) return;
        //对对象进行深层次处理
        for (let key of Object.keys(obj)) {
          //遍历对象 我们需要把属性 对象 及 值 都传递给defineReactive
          defineReactive(obj, key, obj[key]);
        }
      }

      const vm = {
        _data: {
          num: 0,
          movies: [
            { id: "001", movieName: "绿皮书" },
            { id: "002", movieName: "迷雾" },
          ],
          wea: {
            type: "下雨",
            num: 28,
          },
        },
      };
      //调用observe传递参数vm._data
      observe(vm._data);
      vm._data.num++;
       console.log(vm);
    </script>
  </body>
</html>
